import React from 'react';
import {
    View,
    FlatList,
    TouchableOpacity,
    NativeModules,
    Platform,
    Text,
    ScrollView,
    Image,
    StatusBar
} from 'react-native';
import {Ticon} from "react-native-ticon";
import Video from "react-native-video";
import {LoadingView} from "react-native-dsxui";
import {ApiClient, Toast} from "../../utils";
import {Size} from "../../styles";

export default class CourseDetail extends React.Component {

    static navigationOptions = ({navigation}) => ({
        header: null
    });

    constructor(props) {
        super(props);
        this.state = {
            isLoading: true,
            items: [],
            isPause: true, //控制播放器是否播放，下面的代码有解释一个列表只需要一个state控制，而不用数组
            current: 0,//表示当前item的索引，通过这个实现一个state控制全部的播放器,
            section: {}
        };
    }

    render(): React.ReactNode {
        const VIEWABILITY_CONFIG = {
            viewAreaCoveragePercentThreshold: 80,//item滑动80%部分才会到下一个
        };
        const {width, height} = Size.screenSize;
        const STATUSBAR_HEIGHT = Platform.OS === 'ios' ? 0 : NativeModules.StatusBarManager.HEIGHT;
        if (this.state.isLoading) return <LoadingView/>;
        return (<View style={{flex: 1, backgroundColor: '#000'}}>
            <FlatList
                keyExtractor={(item) => item.section_id.toString()}
                data={this.state.items}
                renderItem={({item, index}) => {
                    return (<View style={{width, height: height - STATUSBAR_HEIGHT}}>
                        <Video
                            source={{uri: item.video}}
                            style={{flex: 1, backgroundColor: '#000'}}
                            repeat={true}
                            paused={index === this.state.current ? this.state.isPause : true}
                            resizeMode='contain'
                            poster={item.image}
                        />
                        <TouchableOpacity
                            onPress={() => {
                                this.setState({
                                    isPause: !this.state.isPause,
                                })
                            }}
                            style={{flex: 1, position: 'absolute', width, height: height - STATUSBAR_HEIGHT}}
                        >
                        </TouchableOpacity>
                    </View>);
                }}
                viewabilityConfig={VIEWABILITY_CONFIG}
                pagingEnabled={true}
                horizontal={false}
                showsHorizontalScrollIndicator={false}
                onViewableItemsChanged={this.onViewableItemsChanged}
                getItemLayout={(data, index) => {
                    return {length: height, offset: height * index, index}
                }}
                ListEmptyComponent={() => {
                    return (
                        <View style={{height, alignItems: 'center', justifyContent: 'center'}}>
                            <Text style={{fontSize: 16, color: '#fff', textAlign: 'center'}}>此课程还没有内容</Text>
                        </View>
                    );
                }}
            />
            {this.renderTop()}
        </View>);
    }

    componentDidMount(): void {
        this.props.navigation.addListener('willFocus', () => StatusBar.setHidden(true));
        this.props.navigation.addListener('willBlur', () => StatusBar.setHidden(false));
        this.fetchData();
    }

    fetchData = () => {
        const course_id = this.props.navigation.getParam('course_id', 0);
        ApiClient.get('/course/sections/batchget', {course_id}).then(response => {
            let section = {};
            let items = response.data.items;
            if (items.length > 0) {
                let section = items[this.state.current];
            }

            this.setState({
                items,
                section,
                isLoading: false
            });
        });
    };

    onViewableItemsChanged = ({viewableItems, changed}) => {
        //这个方法为了让state对应当前呈现在页面上的item的播放器的state
        //也就是只会有一个播放器播放，而不会每个item都播放
        //可以理解为，只要不是当前再页面上的item 它的状态就应该暂停
        //只有100%呈现再页面上的item（只会有一个）它的播放器是播放状态
        if (viewableItems.length === 1) {
            const current = viewableItems[0].index;
            const section = this.state.items[current];
            this.setState({
                current,
                section
            });
        }
    };

    renderTop = () => {
        return (
            <View style={{
                flexDirection: 'row',
                position: 'absolute',
                left: 0,
                right: 0,
                top: 20,
                paddingLeft: 20,
                paddingRight: 20,
                paddingBottom: 15
            }}>
                <Ticon size={30} name={"back-light"} color={"#fff"} onPress={() => this.props.navigation.goBack()}/>
                <View style={{flex: 1}}/>
                <View style={{alignItems: 'center', justifyContent: 'center'}}>
                    <Text style={{
                        color: '#fff',
                        fontSize: 18,
                    }} numberOfLines={1}>{this.state.section.title || ''}</Text>
                </View>
                <View style={{flex: 1}}/>
                <TouchableOpacity
                    activeOpacity={1}
                    onPress={() => {
                        ApiClient.post('/video/collect/add', {
                            vid: this.state.items[this.state.current].id
                        }).then(response => {
                            Toast.show('视频收藏成功');
                        }).catch(reason => {
                            console.log(reason);
                        });
                    }}
                >
                    <Image
                        source={require('../../images/common/favorite.png')}
                        style={{
                            width: 30,
                            height: 30,
                            tintColor: '#fff'
                        }}
                    />
                </TouchableOpacity>
            </View>
        );
    }
}
